const { questionList } = require('./dotaQuestion')
const { addScore, getScore } = require('./api/gameList')
class DotaGame {
    constructor(room) {
        this.room = room
        this.isEnd = false
        this.question = {}
        this.questionTimer = null
        this.answerTimer = null
    }

    async start() { // 开始答题
        this.isEnd = false
        const randomIndex = Math.ceil(Math.random() * questionList.length - 1)
        this.question = questionList[randomIndex]
        this.setQusetion()
    }

    end() { // 答题结束
        this.isEnd = true
        this.clearTimer()
        this.question = {}
    }

    // 提问
    setQusetion() {
        this.questionTimer = setTimeout(async () => {
            this.room.say(`本题限时【20】秒,难度【${this.question.level}】\n${this.question.question}\n${this.question.options.join('\n')}`)
        }, 1000);
        this.answerTimer = setTimeout(() => {
            this.room.say(`[旺柴]时间到！很遗憾，没有人能够答对。答案就是【${this.question.answer}】`)
            this.end()
        }, 20000)
    }

    clearTimer() {
        clearTimeout(this.questionTimer)
        clearTimeout(this.answerTimer)
    }

    // 答题
    async getAnswer(answer, contact) {
        if (answer === this.question.answer) {
            const playerName = await contact.name()
            const playerId = await contact.id
            const member = await this.room.member(playerName)
            const roomName = await this.room.topic();
            await addScore({ playerId, playerName, roomName })
            await this.room.say(`[鼓掌]恭喜答对了！答案就是【${answer}】`, member)
            const { data } = await getScore({ playerId })
            await this.room.say(`${playerName}积分+1，总积分【${data}】`)
            this.end()
        }
    }
}

module.exports = {
    DotaGame
}